package com.kxmall.admin.controller.storage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kxmall.admin.controller.storage.service.IKxStorageManageService;
import com.kxmall.common.core.domain.PageQuery;
import com.kxmall.common.core.page.TableDataInfo;
import com.kxmall.common.enums.StorageBusinessStatusType;
import com.kxmall.common.enums.StorageStatusType;
import com.kxmall.common.exception.ServiceException;
import com.kxmall.common.utils.BeanCopyUtils;
import com.kxmall.region.domain.KxRegion;
import com.kxmall.region.mapper.KxRegionMapper;
import com.kxmall.storage.domain.KxStorage;
import com.kxmall.storage.domain.bo.KxStorageBo;
import com.kxmall.storage.domain.vo.KxStorageVo;
import com.kxmall.storage.mapper.KxStorageMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 仓库管理Service业务层处理
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class KxStorageManageServiceImpl implements IKxStorageManageService {

    //private static final String STORAGE_INFO_PREFIX = "STORAGE_INFO_";

    @Autowired
    private KxStorageMapper storageMapper;

    @Autowired
    private KxRegionMapper regionMapper;
    /**
     * 查询仓库管理
     */
    @Override
    public KxStorageVo queryById(Long id) {
        KxStorageVo kxStorageVo = new KxStorageVo();
        KxStorage kxStorage = storageMapper.selectById(id);
        BeanCopyUtils.copy(kxStorage, kxStorageVo);
        if(kxStorage.getProvince() != null){
            KxRegion kxRegion = regionMapper.selectById(kxStorage.getProvince());
            kxStorageVo.setProvinceName(kxRegion.getName());
        }
        if(kxStorage.getCity() != null){
            KxRegion kxRegion = regionMapper.selectById(kxStorage.getCity());
            kxStorageVo.setCityName(kxRegion.getName());
        }
        if(kxStorage.getCounty() != null){
            KxRegion kxRegion = regionMapper.selectById(kxStorage.getCounty());
            kxStorageVo.setCountyName(kxRegion.getName());
        }
        log.info("queryById success! kxStorageVo = {}", kxStorageVo.toString());
        return kxStorageVo;
    }

    /**
     * 查询仓库管理列表
     */
    @Override
    public TableDataInfo<KxStorageVo> queryPageList(KxStorageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<KxStorage> lqw = buildQueryWrapper(bo);
        Page<KxStorage> pageResult = storageMapper.selectPage(pageQuery.build(), lqw);
        List<KxStorageVo> storageVoList = new ArrayList<>();
        if(pageResult != null && pageResult.getRecords().size() > 0){
            for(KxStorage kxStorage : pageResult.getRecords()) {
                KxStorageVo kxStorageVo = new KxStorageVo();
                BeanCopyUtils.copy(kxStorage, kxStorageVo);
                if (kxStorage.getProvince() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxStorage.getProvince());
                    kxStorageVo.setProvinceName(kxRegion.getName());
                }
                if (kxStorage.getCity() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxStorage.getCity());
                    kxStorageVo.setCityName(kxRegion.getName());
                }
                if (kxStorage.getCounty() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxStorage.getCounty());
                    kxStorageVo.setCountyName(kxRegion.getName());
                }
                storageVoList.add(kxStorageVo);
            }
        }
        Page<KxStorageVo> retPageResult = new Page<>();
        BeanCopyUtils.copy(pageResult, retPageResult);
        retPageResult.setRecords(storageVoList);
        log.info("queryPageList success! retPageResult = {}", retPageResult);
        return TableDataInfo.build(retPageResult);
    }

    /**
     * 查询仓库管理列表
     */
    @Override
    public List<KxStorageVo> queryList(KxStorageBo bo) {
        //LambdaQueryWrapper<KxStorage> lqw = buildQueryWrapper(bo);
        //return storageMapper.selectVoList(lqw);
        LambdaQueryWrapper<KxStorage> lqw = buildQueryWrapper(bo);
        List<KxStorage> storageList = storageMapper.selectList(lqw);
        List<KxStorageVo> storageVoList = new ArrayList<>();
        if(storageList != null && storageList.size() > 0){
            for(KxStorage kxStorage : storageList) {
                KxStorageVo kxStorageVo = new KxStorageVo();
                BeanCopyUtils.copy(kxStorage, kxStorageVo);
                if (kxStorage.getProvince() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxStorage.getProvince());
                    kxStorageVo.setProvinceName(kxRegion.getName());
                }
                if (kxStorage.getCity() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxStorage.getCity());
                    kxStorageVo.setCityName(kxRegion.getName());
                }
                if (kxStorage.getCounty() != null) {
                    KxRegion kxRegion = regionMapper.selectById(kxStorage.getCounty());
                    kxStorageVo.setCountyName(kxRegion.getName());
                }
                storageVoList.add(kxStorageVo);
            }
        }
        log.info("queryList success! storageVoList = {}", storageVoList);
        return storageVoList;
    }

    private LambdaQueryWrapper<KxStorage> buildQueryWrapper(KxStorageBo bo) {
        LambdaQueryWrapper<KxStorage> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), KxStorage::getName, bo.getName());
        lqw.eq(bo.getProvince() != null, KxStorage::getProvince, bo.getProvince());
        lqw.eq(bo.getCity() != null, KxStorage::getCity, bo.getCity());
        lqw.eq(bo.getCounty() != null, KxStorage::getCounty, bo.getCounty());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), KxStorage::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getAdcode()), KxStorage::getAdcode, bo.getAdcode());
        lqw.eq(bo.getState() != null, KxStorage::getState, bo.getState());
        lqw.eq(bo.getLongitude() != null, KxStorage::getLongitude, bo.getLongitude());
        lqw.eq(bo.getLatitude() != null, KxStorage::getLatitude, bo.getLatitude());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), KxStorage::getPhone, bo.getPhone());
        lqw.like(StringUtils.isNotBlank(bo.getLeaderName()), KxStorage::getLeaderName, bo.getLeaderName());
        return lqw;
    }

    /**
     * 新增仓库管理
     */
    @Override
    public Boolean insertByBo(KxStorageBo bo) {
        KxStorage kxStorage = BeanUtil.toBean(bo, KxStorage.class);
        kxStorage.setId(0L);
        kxStorage.setState(StorageStatusType.NOMRAL.getCode());
        kxStorage.setOperatingState(StorageBusinessStatusType.BUSINESS.getCode());
        //validEntityBeforeSave(kxStorage);
        boolean flag = storageMapper.insert(kxStorage) > 0;
        if (flag) {
            //RedisUtils.deleteKeys(STORAGE_INFO_PREFIX + "*");
            bo.setId(kxStorage.getId());
        }
        return flag;
    }

    /**
     * 修改仓库管理
     */
    @Override
    public Boolean updateByBo(KxStorageBo bo) {
        KxStorage update = BeanUtil.toBean(bo, KxStorage.class);
        //validEntityBeforeSave(update);
        boolean b = storageMapper.updateById(update) > 0;
        //if (b) {
        //    RedisUtils.deleteKeys(STORAGE_INFO_PREFIX + "*");
        //}
        return b;
    }

    /**
     * 保存前的数据校验
     */
    //private void validEntityBeforeSave(KxStorage entity) {
        //TODO 做一些数据校验,如唯一约束
    //}

    /**
     * 批量删除仓库管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return storageMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean updateStateToNormal(KxStorageBo bo) {
        if (ObjectUtils.isEmpty(bo.getId())) {
            throw new ServiceException("仓库资料不存在");
        }
        if (storageMapper.batchUpdateState(Collections.singletonList(bo.getId()), StorageStatusType.NOMRAL.getCode()) <= 0) {
            throw new ServiceException("仓库资料不存在");
        }
        //else {
        //    RedisUtils.deleteKeys(STORAGE_INFO_PREFIX + "*");
        //}
        return true;
    }

    @Override
    public Boolean updateStateToAbort(KxStorageBo bo) {
        if (ObjectUtils.isEmpty(bo.getId())) {
            throw new ServiceException("仓库资料不存在");
        }
        if (storageMapper.batchUpdateState(Collections.singletonList(bo.getId()), StorageStatusType.ABORT.getCode()) <= 0) {
            throw new ServiceException("仓库资料不存在");
        }
        //else {
        //    RedisUtils.deleteKeys(STORAGE_INFO_PREFIX + "*");
        //}
        return true;
    }

//    @Override
//    public Boolean updateBusinessStateToOpen(KxStorageBo bo) {
//        if (ObjectUtils.isEmpty(bo.getId())) {
//            throw new ServiceException("仓库资料不存在");
//        }
//        if (storageMapper.batchUpdateOperatingState(Collections.singletonList(bo.getId()), StorageBusinessStatusType.BUSINESS.getCode()) <= 0) {
//            throw new ServiceException("仓库资料不存在");
//        } else {
//            RedisUtils.deleteKeys(STORAGE_INFO_PREFIX + "*");
//        }
//        return true;
//    }

//    @Override
//    public Boolean updateBusinessStateToRest(KxStorageBo bo) {
//        if (ObjectUtils.isEmpty(bo.getId())) {
//            throw new ServiceException("仓库资料不存在");
//        }
//        if (storageMapper.batchUpdateOperatingState(Collections.singletonList(bo.getId()), StorageBusinessStatusType.REST.getCode()) <= 0) {
//            throw new ServiceException("仓库资料不存在");
//        } else {
//            RedisUtils.deleteKeys(STORAGE_INFO_PREFIX + "*");
//        }
//        return true;
//    }

//    @Override
//    public List<KxStorageVo> options() {
//        return null;
//    }

//    @Override
//    public String getStorageQrcodeImage() {
//        return null;
//    }

//    @Override
//    public Boolean printTest(KxStorageBo bo) {
//        return null;
//    }


}
